//
//  YMTakePassengerViewController.m
//  PinGJByOwnerSide
//
//  Created by lantaiyuan on 2017/11/9.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

#import "YMTakePassengerViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <Masonry.h>
#import <ReactiveObjC.h>
#import <YYKit.h>
#import "YMTravelTrack.h"
#import "YMStationAnnotation.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import "MANaviRoute.h"
#import "SYDEndTheTripView.h"

@interface YMTakePassengerViewController ()<MAMapViewDelegate, AMapSearchDelegate>
@property(nonatomic, strong) MAMapView *mapView;
@property(nonatomic, strong) MAAnimatedAnnotation* annotation;
@property(nonatomic, assign) CLLocationCoordinate2D * coordinates;
@property(nonatomic, strong) NSArray *lines;
@property(nonatomic, assign) BOOL showStationInfo;
@property(nonatomic, assign) CGFloat preLevel;
@property(nonatomic, strong) NSMutableArray * makers;
@property(nonatomic, strong) AMapSearchAPI *search;
/* 用于显示当前路线方案. */
@property (nonatomic) MANaviRoute * naviRoute;
@property (nonatomic, strong) AMapRoute *route;
@property (nonatomic, strong) YMStationAnnotation *firstAnno;
@property (nonatomic, strong) YMStationAnnotation *lastAnno;
@property (nonatomic, strong) UIButton *startAndEndBtn;
@property (nonatomic, strong) SYDAccount *account;
@property (nonatomic, strong) SYDEndTheTripView *endTheTripView;
@property (nonatomic, strong) UIView *maskView;
@end

@implementation YMTakePassengerViewController

- (NSMutableArray *)makers{
    if (!_makers) {
        _makers = [NSMutableArray array];
    }
    return _makers;
}

- (MAMapView *)mapView{
    if (!_mapView) {
        _mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
        _mapView.y = self.navigationBar.height;
        _mapView.height -= _mapView.y;
        _mapView.zoomLevel = 16.1;
        _mapView.delegate = self;
    }
    return _mapView;
}

- (AMapSearchAPI *)search{
    if (!_search) {
        _search = [[AMapSearchAPI alloc] init];
        _search.delegate = self;
    }
    return _search;
}

- (SYDAccount *)account{
    if (!_account) {
        _account = [SYDAccountTool getAccount];
    }
    return _account;
}

- (UIButton *)startAndEndBtn{
    if (!_startAndEndBtn) {
        _startAndEndBtn = [[UIButton alloc] init];
        _startAndEndBtn.backgroundColor = [UIColor colorWithHexString:@"#2ab650"];
        [_startAndEndBtn setTitle:@"结束行程" forState:UIControlStateNormal];
        [_startAndEndBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _startAndEndBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        [self.view addSubview:_startAndEndBtn];
        
        [_startAndEndBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@0);
            make.right.equalTo(@0);
            make.bottom.equalTo(@0);
            make.height.equalTo(@48);
        }];
    }
    return _startAndEndBtn;
}

-(SYDEndTheTripView *)endTheTripView{
    if (!_endTheTripView) {
        _endTheTripView = [[SYDEndTheTripView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 266, SCREEN_WIDTH, 266)];
    }
    return _endTheTripView;
}

- (UIView *)maskView{
    if (!_maskView) {
        _maskView = [[UIView alloc] initWithFrame:self.view.bounds];
        _maskView.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.7];
        [_maskView addSubview:self.endTheTripView];
    }
    return _maskView;
}

- (void)showEndTravelInfo:(YMConfirmEndTravel *)model{
    self.endTheTripView.model = model;
    [self.view addSubview:self.maskView];
    
    WEAKSELF
    self.endTheTripView.cancelBlock = ^{
        [weakSelf.maskView removeFromSuperview];
        weakSelf.maskView = nil;
    };
    
    self.endTheTripView.sureBlock = ^{
        [weakSelf.maskView removeFromSuperview];
        weakSelf.maskView = nil;
        [weakSelf endTravel];
    };
}

- (void)updateBtnState{
    if ([YMOrderTool getOrderStatus] == YMOrderStatusTraving) {
        [self.startAndEndBtn setTitle:@"结束行程" forState:UIControlStateNormal];
    }else{
        [self.startAndEndBtn setTitle:@"开始行程" forState:UIControlStateNormal];
    }
}

#pragma mark - 导航栏
- (void)navigationBarHandle{
    self.navigationBar.title = @"去接乘客";
    WEAKSELF
    [self leftNavButtonWithImage:[UIImage imageNamed:@"nav_button_return"] action:^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    
    [self rightNavButtonWithImage:[UIImage imageNamed:@"nav_button_call"] action:^{
        NSLog(@"客服电话");
        [weakSelf call];
    }];
}

- (void)loadOrderBaseInfo{
    if (self.order.pathLine.length > 0) {
        self.lines = [self.order.pathLine componentsSeparatedByString:@"|"];
        [self drawLinePath:self.lines];
    }
    [self addMarkers:self.order.carpoolRoute.carpoolRouteStations];
    
    [self updateBtnState];
}

- (BOOL)isArrived:(MAMapPoint)point{
    MAMapPoint userPoint = MAMapPointMake([YMUserLocationTool lat], [YMUserLocationTool lon]);
    BOOL flag = MACircleContainsPoint(userPoint, point, 200);
    return flag;
}

// add station marker
- (void)addMarkers:(NSArray *)stations{
    
    if (self.makers.count > 0) {
        [self.mapView addAnnotations:self.makers];
        return;
    }
    
    stations = [stations sortedArrayUsingComparator:^NSComparisonResult(YMStation  * obj1, YMStation * obj2) {
        if ([obj1.stationNo integerValue] < [obj1.stationNo integerValue]) {
            return NSOrderedAscending;
        }
        return NSOrderedDescending;
    }];
    
    for (YMStation * sta in stations) {
        YMStationAnnotation * anno = [[YMStationAnnotation alloc] init];
        anno.coordinate = CLLocationCoordinate2DMake([sta.stationLat doubleValue], [sta.stationLon doubleValue]);
        anno.station = sta;
        [self.makers addObject:anno];
    }
    [self.mapView addAnnotations:self.makers];
    
    NSArray *routes = [self spilitArray:self.makers size:15];
    
    for (NSArray * array in routes) {
        [self drivePlan:array];
    }
}

- (NSArray *)spilitArray:(NSArray *)array size:(NSInteger)subSize{
    
    NSInteger count = array.count % subSize == 0 ? array.count / subSize : array.count / subSize + 1;
    
    NSMutableArray * subArray = [NSMutableArray array];
    
    for (NSInteger i = 0; i < count; i++) {
        
        NSInteger index = i * subSize;
        
        NSMutableArray * list = [NSMutableArray array];
        
        NSInteger j = 0;
        while (j < subSize && index < array.count) {
            [list addObject:array[index++]];
            j++;
        }
        if (index < array.count) {
            [list addObject:array[index + 1]];
        }
        [subArray addObject:list];
    }
    return subArray;
}

- (void)drivePlan:(NSArray *)makers{
    
    NSMutableArray * points = [NSMutableArray array];
    for (YMStationAnnotation * anno in makers) {
        AMapGeoPoint * point = [AMapGeoPoint locationWithLatitude:anno.coordinate.latitude longitude:anno.coordinate.longitude];
        [points addObject:point];
    }
    
    for (NSInteger i = 0; i < makers.count; i++) {
        if (i != self.makers.count - 1) {
            self.firstAnno = makers.firstObject;
            self.lastAnno = makers.lastObject;
            
            AMapDrivingRouteSearchRequest * navi = [[AMapDrivingRouteSearchRequest alloc] init];
            navi.requireExtension = YES;
            navi.origin = [AMapGeoPoint locationWithLatitude:self.firstAnno.coordinate.latitude longitude:self.firstAnno.coordinate.longitude];
            navi.destination = [AMapGeoPoint locationWithLatitude:self.lastAnno.coordinate.latitude longitude:self.lastAnno.coordinate.longitude];
            navi.waypoints = points;
            [self.search AMapDrivingRouteSearch:navi];
            
            if (i == self.makers.count / 2) {
                YMStationAnnotation * anno = self.makers[self.makers.count / 2];
                [self.mapView setCenterCoordinate:anno.coordinate];
            }
        }
    }
}

// draw line on map
- (void)drawLinePath:(NSArray *)lines{
    CLLocationCoordinate2D linePoints[lines.count];
    NSArray * locs = [self generateLocations];
    for (int i = 0; i < locs.count ; i++) {
        CLLocation * loc = locs[i];
        linePoints[i] = loc.coordinate;
        
        if (i == 0) {
            [self.mapView setCenterCoordinate:loc.coordinate];
            
            MAAnimatedAnnotation * anno = [[MAAnimatedAnnotation alloc] init];
            anno.coordinate = loc.coordinate;
            self.annotation = anno;
        }
    }
    //    MAPolyline * polyline = [MAPolyline polylineWithCoordinates:linePoints count:locs.count];
    //    [self.mapView addOverlay:polyline];
    [self.mapView addAnnotation:self.annotation];
}

- (NSMutableArray *)generateLocations{
    NSMutableArray * locaitons = [NSMutableArray array];
    for (int i = 0; i < self.lines.count; i++) {
        NSString * temp = self.lines[i];
        NSArray * points = [temp componentsSeparatedByString:@","];
        CLLocation * loc = [[CLLocation alloc] initWithLatitude:[points[1] doubleValue] longitude:[points[0] doubleValue]];
        [locaitons addObject:loc];
    }
    
    return locaitons;
}

- (void)go:(CLLocationCoordinate2D *)coordinates count:(NSInteger)count completaCallback:(void(^)(BOOL isFinished))completaCallback {
    [self.annotation addMoveAnimationWithKeyCoordinates:coordinates count:count withDuration:10 withName:nil completeCallback:^(BOOL isFinished) {
        completaCallback(isFinished);
    }];
}

- (void)startTravel{
    YMStationAnnotation * firstSta = self.makers.firstObject;
    if (![self isArrived:MAMapPointMake([firstSta.station.stationLat doubleValue], [firstSta.station.stationLon doubleValue])]) {
        [SVProgressHUD displayInfoWithStatus:@"您还未到达指定起点，无法开始行程。"];
        return;
    }
    WEAKSELF
    [[SYDNetwork shareTool] startJourneyWithCityCode:self.account.cityCode lat:[YMUserLocationTool latitude] lon:[YMUserLocationTool longitude] orderNo:[YMOrderTool getOrderNo] userId:self.account.userId success:^(NSURLSessionDataTask *task, id responseObject) {
        @try{
            if (responseObject[@"success"]) {
                [YMOrderTool saveOrderStatus:YMOrderStatusTraving];
                [weakSelf updateBtnState];
                if (weakSelf.trvaleBlock) {
                    weakSelf.trvaleBlock();
                }
            }
        }
        @catch(NSException * e){
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {

    }];
}

- (void)confirmEndTravel{
    YMStationAnnotation * lastSta = self.makers.lastObject;
    if (![self isArrived:MAMapPointMake([lastSta.station.stationLat doubleValue], [lastSta.station.stationLon doubleValue])]) {
        [SVProgressHUD displayInfoWithStatus:@"您还未到达指定终点，无法结束行程"];
        return;
    }
    
    WEAKSELF
    [[SYDNetwork shareTool] confirmEndingJourneySuccess:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"-- :%@",[responseObject modelToJSONString]);
        
        @try{
            YMConfirmEndTravel * travel = [YMConfirmEndTravel mj_objectWithKeyValues:responseObject[@"obj"]];
            [weakSelf showEndTravelInfo:travel];
            NSLog(@"%@", travel.yid);
        }
        @catch(NSException * e){
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

- (void)endTravel{
    WEAKSELF
    [[SYDNetwork shareTool] endJourneyWithCityCode:self.account.cityCode lat:[YMUserLocationTool latitude] lon:[YMUserLocationTool longitude] orderNo:self.order.matchId userId:self.order.userId success:^(NSURLSessionDataTask *task, id responseObject) {
        @try{
            if (responseObject[@"success"]) {
                [YMOrderTool saveOrderStatus:YMOrderStatusListen];
                [weakSelf updateBtnState];
                if (weakSelf.trvaleBlock) {
                    weakSelf.trvaleBlock();
                }
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
        }
        @catch(NSException * e){
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {

    }];
}


- (void)call{
    NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"telprompt://%@",SERVER_TEL];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadOrderBaseInfo];
    [self.view insertSubview:self.mapView belowSubview:self.startAndEndBtn];
    [self navigationBarHandle];
    
    WEAKSELF
    [[self.startAndEndBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIButton * x) {
        if ([YMOrderTool getOrderStatus] != YMOrderStatusTraving) {
            [weakSelf startTravel];
        }else{
            [weakSelf confirmEndTravel];
        }
    }];
}

- (void)presentCurrentCourse{
    MANaviAnnotationType type = MANaviAnnotationTypeDrive;
    self.naviRoute = [MANaviRoute naviRouteForPath:self.route.paths.lastObject
                                      withNaviType:type
                                       showTraffic:YES
                                        startPoint:[AMapGeoPoint locationWithLatitude:self.firstAnno.coordinate.latitude longitude:self.firstAnno.coordinate.longitude]
                                          endPoint:[AMapGeoPoint locationWithLatitude:self.lastAnno.coordinate.latitude longitude:self.lastAnno.coordinate.longitude]
                      ];
    [self.naviRoute addToMapView:self.mapView];
}

#pragma mark - MAMapViewDelegate

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{
    if ([annotation isKindOfClass:[YMStationAnnotation class]]){ // station
        if (_showStationInfo) {
            NSString *reuseIndetifier = @"staInfoReuseIndetifier";
            YMStationAnnotationView * annotationView = (YMStationAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
            if (annotationView == nil) {
                annotationView = [[YMStationAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
            }
            YMStationAnnotation * anno = (YMStationAnnotation *)annotation;
            annotationView.station = anno.station;
            return annotationView;
        }else{
            NSString *reuseIndetifier = @"staReuseIndetifier";
            YMStationAnnotationIconView * annotationView = (YMStationAnnotationIconView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
            if (annotationView == nil) {
                annotationView = [[YMStationAnnotationIconView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
            }
            return annotationView;
        }
    }else if ([annotation isKindOfClass:[MAPointAnnotation class]]) { // car
        NSString *reuseIndetifier = @"myReuseIndetifier";
        MAAnnotationView * annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil) {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
            UIImage * image = [UIImage imageNamed:@"icon_car"];
            annotationView.image = image;
        }
        return annotationView;
    }
    return nil;
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:(MAPolyline *)overlay];
        polylineRenderer.lineWidth    = 5.f;
        [polylineRenderer loadStrokeTextureImage:[UIImage imageNamed:@"arrowTexture"]];
        return polylineRenderer;
    }
    
    return nil;
}

- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    NSLog(@"--level-%f", mapView.zoomLevel);
    if (_preLevel == mapView.zoomLevel) {
        return;
    }
    
    if (mapView.zoomLevel > 16) {
        _preLevel = mapView.zoomLevel;
        _showStationInfo = YES;
    }else{
        _showStationInfo = NO;
    }
    
    [mapView removeAnnotations:self.makers];
    [self addMarkers:self.makers];
}

#pragma mark - AMapSearchDelegate
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"%@",error.localizedDescription);
}

- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response{
    NSLog(@"%@",response);
    self.route = response.route;
    [self presentCurrentCourse];
    
}

@end
